package com.example.bluetooth_application;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.bluetooth_application.activity.IatActivity;
import com.example.bluetooth_application.utils.BluetoothDeviceListActivity;
import com.example.bluetoothapplication.utils.BluetoothUtils;

import java.util.ArrayList;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {

    public static BluetoothUtils bluetoothUtils;
    private boolean isBTAvailable;
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQ_PERMISSION_CODE = 1;
    // 蓝牙权限列表
    public ArrayList<String> requestList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getPermision();
        buttonInit();
        bluetoothUtils = new BluetoothUtils();
        isBTAvailable = bluetoothUtils.isBlueToothAvailable();
        pageJumpy();

    }

    /**
     * 页面跳转
     */
    public void pageJumpy(){
        Button voice_button = findViewById(R.id.voice_button);
        voice_button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, IatActivity.class);
                startActivity(intent);
            }
        });

    }

    /**********************
     获取蓝牙设备名，并进行蓝牙连接
     **********************/
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CONNECT_DEVICE) {
            // 当DeviceListActivity返回与设备连接的消息
            if (resultCode == Activity.RESULT_OK) {
                // 得到链接设备的MAC
                String address = Objects.requireNonNull(data.getExtras()).getString(BluetoothDeviceListActivity.EXTRA_DEVICE_ADDRESS, "");
                // 得到BluetoothDevice对象
                if (!TextUtils.isEmpty(address)) {
                    BluetoothDevice device = bluetoothUtils.getBluetoothAdapter().getRemoteDevice(address);
                    boolean conSt = bluetoothUtils.connectThread(device);
                    if (conSt) {
                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }

    /**
     * andriod 12 需要动态动态申请权限 不然无法连接蓝牙
     */
    public void getPermision(){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
            requestList.add(android.Manifest.permission.BLUETOOTH_SCAN);
            requestList.add(android.Manifest.permission.BLUETOOTH_ADVERTISE);
            requestList.add(android.Manifest.permission.BLUETOOTH_CONNECT);
            requestList.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
            requestList.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
            requestList.add(Manifest.permission.BLUETOOTH);
        }
        if(requestList.size() != 0){
            ActivityCompat.requestPermissions(this, requestList.toArray(new String[0]), REQ_PERMISSION_CODE);
        }
    }

    /****************************************
     * 按键初始化
     *****************************************/
    public void buttonInit(){
        // 发送测试
        findViewById(R.id.send_button).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN && bluetoothUtils.isConnected()) {
                    bluetoothUtils.write("1");
                    Toast.makeText(MainActivity.this,"发送了1",Toast.LENGTH_SHORT).show();
                }
                view.performClick();
                return false;
            }
        });

        // 蓝牙连接按钮
        findViewById(R.id.bluetooth_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (!isBTAvailable) {
                    Toast.makeText(MainActivity.this, "蓝牙是不可用的", Toast.LENGTH_LONG).show();
                } else {
                    String[] items = new String[]{"打开蓝牙", "连接蓝牙", "断开蓝牙"};
                    AlertDialog dialog;
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this).setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            switch (i) {
                                case 0:   //打开蓝牙
                                    bluetoothUtils.openBlueTooth(MainActivity.this);
                                    break; //可选
                                case 1:  //连接蓝牙
                                    if (!isBTAvailable) {
                                        Toast.makeText(MainActivity.this, "蓝牙是不可用的", Toast.LENGTH_LONG)
                                                .show();
                                    } else if (!bluetoothUtils.getBluetoothAdapter().isEnabled()) {
                                        Toast.makeText(MainActivity.this, "未打开蓝牙", Toast.LENGTH_SHORT)
                                                .show();
                                    } else {
                                        Intent serverIntent = new Intent(MainActivity.this,
                                                BluetoothDeviceListActivity.class);   //跳转到蓝牙扫描连接页面
                                        startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
                                    }
                                    break; //可选
                                case 2:// 断开连接
                                    if (!bluetoothUtils.isConnected()) {
                                        Toast.makeText(MainActivity.this, "无连接", Toast.LENGTH_SHORT)
                                                .show();
                                    } else {
                                        Toast.makeText(MainActivity.this, "已断开连接", Toast.LENGTH_SHORT)
                                                .show();
                                        bluetoothUtils.cancelConnect();
                                    }
                                    break;
                                default: //可选
                                    //语句
                            }
                        }
                    });
                    dialog = builder.create();
                    dialog.show();
                }
            }
        });
    }





}